import { defineStore } from 'pinia';
import { defaultUserInfo } from '@/config/app';
import Tools from '@/utils/tools';
import useToast from '@/hooks/useToast';
import socketService from '@/utils/socketService';
import to from '@/utils/to';
import useModal from '@/hooks/useModal';
import { EEquipType } from '@/enum/equip';
import { navigate } from '@/utils/navigate';
import eventBus from '@/utils/eventBus';

export interface IBeeperParams {
  queryType: number;
  latitude: string | number;
  longitude: string | number;
  provinceName: string;
  cityName: string;
  areaName: string;
}

export interface AppState {
  systemInfo: UniApp.GetSystemInfoResult;
  menuInfo: UniApp.GetMenuButtonBoundingClientRectRes;
  userInfo: ILoginResponse;
  btnInformation?: IServerBtnListBtnList;
  beeperParams: IBeeperParams;
  beeperId: number;
  token?: string;
  tabbarHeight: number;
  headerHeight: number;
  shoppingCart: IProductInformation[];
  registerData: {
    date: number; // 挂号时间 例如 01、02
    doctorId: number; // 挂号医生id
    timeStamp: number; // 时间戳
  };
  IMOU_TOKEN: string; // 乐橙云平台token
}
const { VITE_SOCKET_URL } = import.meta.env;
const { showToast } = useToast();
const { showModal } = useModal();
const useAppStore = defineStore('app', {
  state: (): AppState => ({
    systemInfo: uni.getSystemInfoSync(),
    menuInfo: uni.getMenuButtonBoundingClientRect(),
    userInfo: Tools.deepClone(defaultUserInfo),
    beeperId: 0,
    beeperParams: { queryType: 1, latitude: '', longitude: '', provinceName: '', cityName: '', areaName: '' },
    tabbarHeight: uni.getSystemInfoSync().safeAreaInsets!.bottom + 50 || 84,
    headerHeight: 0,
    shoppingCart: [],
    registerData: { date: 0, doctorId: 0, timeStamp: 0 },
    IMOU_TOKEN: '',
  }),
  actions: {
    updateTabbarHeight() {
      this.tabbarHeight = this.systemInfo.safeAreaInsets!.bottom + 50 || 84;
      this.headerHeight = this.menuInfo.height + this.menuInfo.top + 8;
    },
    clearLoginStatus() {
      this.$patch({ token: undefined, beeperId: 0, userInfo: Tools.deepClone(defaultUserInfo), shoppingCart: [] });
      socketService.close();
    },
    updateShoppingCart(action: { type: 'add' | 'remove'; data: IProductInformation }, callback?: (shoppingCart: IProductInformation[]) => void) {
      const { type, data } = action;
      const shoppingCart = Tools.deepClone(this.$state.shoppingCart);
      const productIndex = shoppingCart.findIndex((item) => item.goodsId === data.goodsId);
      if (type === 'add') {
        if (productIndex !== -1) {
          if (shoppingCart.some((item) => item.doctorId === data.doctorId)) {
            showToast('挂号产品不可增加数量');
            return;
          }
          // 如果商品已在购物车中，增加数量
          shoppingCart[productIndex].nums += 1;
        } else {
          if (shoppingCart.some((item) => item.doctorId) || shoppingCart.length !== 0) {
            showToast('挂号产品不可与其他产品同时加入购物车下单');
            return;
          }
          if (shoppingCart.find((item) => item.goodsType === 15)) {
            showToast('购物车中有补差价产品，不能同其他产品一起购买');
            return;
          }
          // 如果商品不在购物车中，添加商品，初始数量为1
          if (data.doctorId) {
            setTimeout(() => {
              this.$patch({ registerData: { ...this.registerData, doctorId: data.doctorId } });
            }, 200);
          }
          shoppingCart.push({ ...data, nums: 1 });
        }
      } else if (type === 'remove') {
        if (productIndex !== -1) {
          if (shoppingCart[productIndex].nums > 1) {
            // 数量大于1时，减少数量
            shoppingCart[productIndex].nums -= 1;
          } else {
            // 数量为1时，直接移除商品
            shoppingCart.splice(productIndex, 1);
          }
        }
      }
      if (callback) callback(shoppingCart);
      this.$state.shoppingCart = shoppingCart;
    },
    updateShoppingCartSku(action: { type: 'add' | 'remove'; data: IProductInformation }, callback?: (shoppingCart: IProductInformation[]) => void) {
      const { type, data } = action;
      const shoppingCart = Tools.deepClone(this.$state.shoppingCart);
      const productIndex = shoppingCart.findIndex((item) => item.goodsId === data.goodsId && item.sku === data.sku);
      const hasPackage = data.goodsType === 2 && shoppingCart.find((item) => item.goodsId === data.goodsId);
      if (type === 'add') {
        if (productIndex !== -1) {
          shoppingCart[productIndex].nums += data.nums;
        } else {
          // 如果是套餐产品 活动是不会算到每个规格，所以规格不一样但是每加一个同样的套餐时，maxNum -1
          if (hasPackage) {
            shoppingCart.forEach((item, index) => {
              if (item.goodsId === data.goodsId) {
                shoppingCart[index].active = { ...shoppingCart[index].active, maxNum: shoppingCart[index].active.maxNum - 1 };
              }
            });
            shoppingCart.push({ ...data, active: { ...data.active, maxNum: data.active.maxNum - shoppingCart.filter((item) => item.goodsId === data.goodsId).length } });
          } else {
            shoppingCart.push(data);
          }
        }
      } else if (type === 'remove') {
        if (productIndex !== -1) {
          if (shoppingCart[productIndex].nums > 1) {
            shoppingCart[productIndex].nums -= 1;
          } else {
            if (hasPackage) {
              shoppingCart.forEach((item, index) => {
                if (item.goodsId === data.goodsId && shoppingCart[index].active) {
                  shoppingCart[index].active = { ...shoppingCart[index].active, maxNum: shoppingCart[index].active.maxNum + 1 };
                }
              });
            }
            shoppingCart.splice(productIndex, 1);
          }
        }
      }
      if (callback) callback(shoppingCart);
      this.$state.shoppingCart = shoppingCart;
    },
    updateShoppingCartHours(action: IProductInformation[]) {
      action.forEach((newProduct) => {
        const existingProduct = this.$state.shoppingCart.find((item) => item.goodsId === newProduct.goodsId);
        // 替换 goodsHours
        if (existingProduct) {
          existingProduct.goodsHours = newProduct.goodsHours;
        }
      });
    },
    removeShoppingCart(action: number | undefined) {
      if (action) {
        this.$state.shoppingCart = this.$state.shoppingCart.filter((item) => item.goodsId !== action);
      } else {
        this.$state.shoppingCart = [];
      }
    },
    async connectSocketMessage() {
      if (!this.$state.token) return;
      const [err] = await to(socketService.connect(VITE_SOCKET_URL));
      if (err) return;
      const [sendErr] = await to(socketService.sendMessage({ refresh: this.userInfo.userId }));
      if (sendErr) return;
      socketService.on('message', async ({ _, source }) => {
        if (Number(source) < 32) return;
        const modal = await showModal(`${EEquipType[source - 30]}报警，请及时处理`, {}, '警告');
        eventBus.emit('callAlarmNotification');
        if (modal.confirm) {
          navigate({ url: '/pages/equipment/index', type: 'switchTab' });
        }
      });
    },
  },
  persist: [
    { key: 'app', storage: localStorage, pick: ['userInfo', 'beeperId', 'btnInformation', 'shoppingCart'] },
    { key: 'token', storage: localStorage, pick: ['token'] },
    { key: 'IMOU_TOKEN', storage: localStorage, pick: ['IMOU_TOKEN'] },
  ],
});

export default useAppStore;
